package com.agh.portal.web;

import java.util.HashMap;
import java.util.Map;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.agh.portal.data.Votable;
import com.agh.portal.service.PersistanceUtils;

@Controller
@RequestMapping("/ajax")
public class AjaxController {

    @RequestMapping(value="voteUp/{entityName}", method = RequestMethod.POST)
    public @ResponseBody Map<String,Object> voteUp(@PathVariable String entityName, @RequestParam Long entityId, @RequestParam Long userId){ 
    	System.out.println("voteUp/"+entityName + " entityId: "+entityId + " userId:"+userId);
    	Map<String,Object> response = new HashMap<String,Object>();
    	try{
        	Votable votableEntity = PersistanceUtils.addGoodVote(entityName, entityId, userId);
        	response.put("goodVoteCount", votableEntity.getGoodVoteCount());
        	response.put("badVoteCount", votableEntity.getBadVoteCount());
    	}catch(Exception ex){
    		response.put("status", "error");
    		response.put("errorMessage", ex.toString());
    	}
    	return response;
    }
    
    @RequestMapping(value="/voteDown{entityName}", method = RequestMethod.POST)
    public @ResponseBody Map<String,Object> voteDown(@PathVariable String entityName, @RequestParam Long entityId, @RequestParam Long userId){   
    	Map<String,Object> response = new HashMap<String,Object>();
    	System.out.println("voteDown/"+entityName + " entityId: "+entityId + " userId:"+userId);
    	try{
        	Votable votableEntity = PersistanceUtils.addBadVote(entityName, entityId, userId);
        	response.put("goodVoteCount", votableEntity.getGoodVoteCount());
        	response.put("badVoteCount", votableEntity.getBadVoteCount());
    	}catch(Exception ex){
    		response.put("status", "error");
    		response.put("errorMessage", ex.toString());
    	}
    	return response;
    }
	
}
